/**
 * 
 */
package edu.unr.cater.npap.server;

import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;

import com.google.gwt.user.client.ui.RootLayoutPanel;
import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import edu.unr.cater.npap.client.AuthService;
import edu.unr.cater.npap.server.security.CustomUserAuthentication;
import edu.unr.cater.npap.server.security.UserAuthenticationProvider;

/**
 * @author Hao
 * 
 */
@SuppressWarnings("serial")
public class AuthServiceImpl extends RemoteServiceServlet implements
		AuthService {

	/*
	 * (non-Javadoc)
	 * 
	 * @see edu.unr.cater.npap.client.AuthService#retrieveUsername()
	 */
	public String retrieveUsername() {
		// TODO Auto-generated method stub
		Authentication authentication = SecurityContextHolder.getContext()
				.getAuthentication();
		if (authentication == null) {
			System.out.println("Not logged in");
			return null;
		} else {
			return (String) authentication.getPrincipal();
		}

	}

	public Boolean isAuthorized() {
		// TODO Auto-generated method stub
		Authentication authentication =  SecurityContextHolder
				.getContext().getAuthentication();
		if (authentication == null) {
			System.out.println("Not logged in");
			return false;
		}

		if (authentication.getPrincipal().toString().equals("anonymousUser"))
			return false;
		else
			return true;

	}

	public Boolean logIn(String username, String password) {
		// TODO Auto-generated method stub
		UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(username, password);

	    // Authenticate the user
		UserAuthenticationProvider authenticationManager=new UserAuthenticationProvider();
	    Authentication authentication = authenticationManager.authenticate(authRequest);	    
	    SecurityContext securityContext = SecurityContextHolder.getContext();
	    securityContext.setAuthentication(authentication);
	    if(authentication.getPrincipal().toString().equals(username))
	    	return true;
	    else
	    	return false;

//	    // Create a new session and add the security context.
//	    HttpSession session = request.getSession(true);
//	    session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext);
	}

	@Override
	public Boolean logOut() {
		// TODO Auto-generated method stub
		SecurityContext securityContext = SecurityContextHolder.getContext();
	    securityContext.setAuthentication(null);
		return true;
	}

}
